﻿var ct = new clickTrack('renren_publish');
(function() {
  var apiKey = "4fc95cc0348d41b4821dd9ade8dd1ab9";
  var oUser={
    'id':'',
    'name':'',
    'img':''
  };
  //存储表情
  var aEmotions = [];
  var timerId = null;
  var timeInterval = 10*60*1000;
  var hasValidation = false;
  //每页的显示数量
  var NUM_PER_PAGE = 10;
  var CUR_PAGE = 0;
  var TOTAL_NUM = 0;
  //HZH
  var StatusFeedsPages = null;
  //正在编辑的textarea,且打开了表情
  var currentTextObj = {};
  //鼠标是否在表情面板里
  var inEm = false;
  var arthCache = {};
  var statusFeeds = {};
  var inOnEm = false;
  //当前用户处于编辑状态
  var bIsOnEdit = false;
  var isConnectedAlready = false;
  
  var oTabSelectCallback = {
    'tab_all':onTabAllSelected,
    'tab_status':onTabStatusSelected,
    'tab_blog':onTabBlogSelected,
    'tab_pic':onTabPicSelected,
    'tab_share':onTabShareSelected
  }
  
  XN_RequireFeatures(["EXNML"], function() {
    XN.Main
    .init(
      apiKey,
      "/xd_receiver.html",
      {
        "ifUserConnected" : connectedSuccess,
        "acceptCookie" : false,
        "forceLoginPopup": true
      });

  });

  _gel('login_btn').onclick = onLogin;

  function onLogin() {
    XN.Connect.requireSession(function() {
      });

  }

  function connectedSuccess() {
    XN.Main.apiClient.users_hasAppPermission(apiKey, function(result, ex) {
      if (!ex) {
        if (result.result) {

        } else {
          // if has permission
		  if(isConnectedAlready) {
			//console.log('have conneted');
			return;
		  }
		  isConnectedAlready = true;
          _gel('login_page').style.display = 'none';
          _gel('main_page').style.display = '';
          initMainPage();
        }
      }
    });
  }
  function initMainPage(){
    getUserInfo();
    addDomListener();
    initEmoticon();
    getEvents();
    startTimer(0);
  }
  /**
   * 绑定事件
   */
  function addDomListener(){  
    _gel('rr_logo').onclick = toRenrenPage;
    _gel('status_set').onclick = onStatusSet;
    _gel('user_status_input').onclick = onStatusInput;
    _gel('user_status_input').onblur = onStatusInputDone;
	_gel('user_status_input').onfocus = function(){
		_gel('textNow').style.dispaly = '';
	};
    _gel('user_status_input').onkeydown = onStatusInputing;
    _gel('tab_status_content').onclick = onClickListener;
    _gel('contentAll').onscroll = closeEmoticon;
    _gel('btn_logout').onclick = onLogout;
    _gel('btn_permission').onclick = onCheckPermission;
    //change tabs
    _gel('menutab').onclick = function(e){
      e=e?e:window.event;
      var target = e.target?e.target:e.srcElement;
      if(target.tagName.toUpperCase()=='A' && !_hasClass(target,'not_menu_tab')){
        if(_gel('pagination')) {
          _gel('pagination').parentNode.removeChild(_gel('pagination'));
        }
        changeTab(target);
        return false;
      }
    }
    //tab content click listener
    _gel("tab_all_content").onclick = function(e){
      e=e?e:window.event;
      onTabAllDomClick(e);
      //return false;
    }
    _gel("tab_blog_content").onclick = function(e){
      e=e?e:window.event;
      onTabBlogDomClick(e);
      //return false;
    }
    _gel("tab_pic_content").onclick = function(e){
      e=e?e:window.event;
      onTabPicDomClick(e);
      //return false;
    }
    _gel("tab_share_content").onclick = function(e){
      e=e?e:window.event;
      onTabShareDomClick(e);
      //return false;
    }
  }
  function getEvents() {
    XN.Main.apiClient.connect_getEvents(function(result, ex) {
      if (!ex) {
        if (result.message > 0) {
          _gel('msgbar_1').style.display = '';
          _gel('msgbar_1').firstChild.nodeValue = result.message;
        } else {
          _gel('msgbar_1').style.display = 'none';
        }
        if (result.fangle > 0) {
          _gel('msgbar_2').style.display = '';
          _gel('msgbar_2').firstChild.nodeValue = result.fangle;
        } else {
          _gel('msgbar_2').style.display = 'none';
        }

        if (result.notification > 0) {
          _gel('msgbar_3').style.display = '';
          _gel('msgbar_3').firstChild.nodeValue = result.notification;
        } else {
          _gel('msgbar_3').style.display = 'none';
        }

        if (result.friend_request > 0) {
          _gel('msgbar_4').style.display = '';
          _gel('msgbar_4').firstChild.nodeValue = result.friend_request;
        } else {
          _gel('msgbar_4').style.display = 'none';
        }

        if (result.message || result.fangle || result.notification
          || result.friend_request) {
          _gel('msgbar').style.display = '';
        } else {
          _gel('msgbar').style.display = 'none';
        }
      }
    })
  }
/**
 * 登陆成功后做的初始化操作
 */
  function onStatusSet() {
    var oInput = _gel('user_status_input');
    _removeClass(_gel('user_status_input_out'),'on');
    closeEmoticon();
    if(_hasClass(oInput,'begin')) {
      return;
    }
    var text = oInput.value.substring(0, 140);
    if(!text){
      oInput.onblur();
      oInput.blur();
      return;
    }
	if(!_trim(text)) {
		_addClass(_gel('user_status_input'),'begin');
		_gel('user_status_input').value = '你正在干嘛?';
		_gel('user_status_input').blur();
		return;
	}
    _gel('status_update').innerHTML = '状态发布中...';
	var sid = _gel('user_status_input').getAttribute('sid');
	var uid = _gel('user_status_input').getAttribute('uid');
	try {
		if((!sid && !uid) || (sid == 'no' && uid == 'no')) {
			XN.Main.apiClient.status_set(text,statusSetCallback);
		} else {
			XN.Main.apiClient.status_set(text,parseInt(sid),parseInt(uid),statusSetCallback);
		}
	} catch(e) {
		//_gel('tab_status_content').style.display='';
		//_gel('validate_wrap').style.display='none';
		_gel('textNow').style.display = '';
		_gel('status_update').innerHTML = '<span class="font3">网络繁忙，状态更新失败</span>';
		setTimeout(function(){
		  getStatus(handleMyStatus);
		},3000);
	}
  }
  
  function statusSetCallback(result,ex) {
    _gel('textNow').style.display = '';
	_addClass(_gel('user_status_input'),'begin');
	_gel('user_status_input').value = '你正在干嘛?';
	_gel('user_status_input').setAttribute('sid','no');
	_gel('user_status_input').setAttribute('uid','no');
	if (!ex) {
		// 成功，成功后到这里添加显示到界面上
		getStatus(handleMyStatus);
		return;
	} else {
		// 失败，3秒后回到原来的状态
		switch(ex.userData.error_code) {
			case 10402 : {
				_gel('status_update').innerHTML = '<span class="font3">您的发言有不恰当内容，状态更新失败</span>';
				break;
			}
			case 20201 : {
				_gel('status_update').innerHTML = '<span class="font3">您尚未授权，授权后可以在此发布状态</span>';
				//_gel('tab_status_content').style.display='none';
				//_gel('validate_wrap').style.display='';
				break;
			}
			case 452 : {
				_gel('status_update').innerHTML = '<span class="font3">您尚未登录，状态发布失败！</span>';
				setTimeout(function(){
					window.location.reload(true);
				},3000);
				return;
			}
			default : {
				if(ex.userData.error_msg) {
					_gel('status_update').innerHTML = '<span class="font3">'+ex.userData.error_msg+'</span>';
				} else{
					_gel('status_update').innerHTML = '<span class="font3">未知的错误</span>';
				}
		}
	}
	setTimeout(function(){
	  getStatus(handleMyStatus);
	},3000);
  }
  }
  
  function toRenrenPage() {
    window.open("http://www.renren.com/home.do");
  }
  function onStatusInput() {
    if (_hasClass(this, 'begin')) {
      _removeClass(this, 'begin');
      this.value = '';
    }
    _addClass(_gel('user_status_input_out'),'on');
	_gel('textNow').style.display = 'none';
    showEmoticon(this);
  }
  function onStatusInputDone(){
    if(!inEm) {
		if(!_gel('user_status_input').value){
          _addClass(_gel('user_status_input'),'begin');
          _gel('user_status_input').value = '你正在干嘛?';
		  _removeClass(_gel('user_status_input_out'),'on');
		  _gel('textNow').style.display = '';
        }
		closeEmoticon();
	}
  }
  function onStatusInputing(e){
    e=e?e:window.event;
    var keyCode=e.keyCode||e.which||e.charCode;
    if(keyCode==13){
      if(e.preventDefault){
        e.preventDefault();
      }else{
        e.returnValue=false;
      }
	  _gel('textNow').style.display = '';
      onStatusSet();
    }else{
      if(_hasClass(this,'begin')){
        _removeClass(this,'begin');
        this.value='';
      }
    }
  }
  /**
   * 显示表情面板
   */
  function showEmoticon(area,opt_isLeft) {
    currentTextObj.text = area;
    currentTextObj.loc = opt_isLeft || false;
    //currentTextarea = area;
	if(hasValidation) {
		_gel('publisher_emotion').style.display = '';
	}
    handleScroll();
  }
  /**
   * 处理滚动导致的表情弹出窗定位不准确
   */
  function handleScroll() {
    if(!_gel('publisher_emotion').style.display) {
		var loc = getLoc(currentTextObj.text,currentTextObj.loc);
		var bottomLoc = getLoc(_gel('contentAll'),false);
		var allHeight = bottomLoc.y + _gel('contentAll').offsetHeight;
		var eHeight = loc.y + _gel('publisher_emotion').offsetHeight + getHeight(currentTextObj.text);
		if(allHeight - eHeight > 0) {
			_gel('publisher_emotion').style.top = ( loc.y + getHeight(currentTextObj.text) ) + 'px';
		} else {
			_gel('publisher_emotion').style.top = loc.y - getHeight(_gel('publisher_emotion')) + 'px';;
		}
        if(currentTextObj.loc) {
          var eWidth = getWidth(_gel('publisher_emotion'));
          _gel('publisher_emotion').style.left = loc.x + getWidth(currentTextObj.text) - eWidth + 'px';
        } else {
          _gel('publisher_emotion').style.left = (loc.x - 1) + 'px'
        }
    }
  }
  /**
   * 关闭表情
   */
  function closeEmoticon() {
    currentTextObj = {};
    _gel('publisher_emotion').style.display = 'none';
  }
  /**
   * 初始化表情
   */
  function initEmoticon() {
    XN.Main.apiClient.status_getEmoticons('recent', function(result,ex) {
      if(!ex) {
        var ul = first(_gel('publisher_emotion'));
        for (var i = 0; result[i]; i++) {
          var li = creatEmotionLi(result[i]);
          ul.appendChild(li);
        }

      }
    });
  };
  /**
   * 创建一个表情li
   */
  function creatEmotionLi(emotion) {
    var li = document.createElement('li');
    li.title = emotion.desc;
    var a = document.createElement('a');
    a.href = 'javascript:void(0)';
    var img = document.createElement('img');
    img.alt = emotion.desc;
    img.src = emotion.icon;
    a.appendChild(img);
    li.appendChild(a);
    a.onclick = handleEmotion(emotion.emotion);
    a.setAttribute('em','true');
    img.setAttribute('em','true');
    return li;
  }
  /**
   * 处理点击表情的事件
   */
  function handleEmotion(emotion) {
  return function() {
    if(currentTextObj && currentTextObj.text) {
      var text = currentTextObj.text;
      text.focus();
      text.value += emotion;
    }
  }
  }
  
  _gel('publisher_emotion').onmouseover = function() {
    inEm=true;
  };
  _gel('publisher_emotion').onmouseout = function() {inEm=false;};

  
  function onTabAllDomClick(e){
    var target = e.srcElement?e.srcElement:e.target;
    if(target.tagName.toUpperCase()=='A'&&_hasClass(target,'fold')){      
      foldComments(target);
    }else if(target.tagName.toUpperCase()=='A'&&_hasClass(target,'show_all')){
      displayAllComments(target);
    }else if(target.tagName.toUpperCase()=='A'&&_hasClass(target,'reply')){
      replyUserComments(target);
    }else if(target.tagName.toUpperCase()=='A'&&_hasClass(target,'fwd')){
      fwdMessage(target);
    }else if(target.tagName.toUpperCase()=='IMG'&&_hasClass(target,'fl')){
      var uid = target.getAttribute('uid');
      onPicClick(uid);
    }
  }
  function onTabBlogDomClick(e){
    var target = e.srcElement?e.srcElement:e.target;
    if(target.tagName.toUpperCase()=='A'&&_hasClass(target,'fold')){      
      foldComments(target);
    }else if(target.tagName.toUpperCase()=='A'&&_hasClass(target,'show_all')){
      displayAllComments(target);
    }else if(target.tagName.toUpperCase()=='A'&&_hasClass(target,'reply')){
      replyUserComments(target);
    }else if(target.tagName.toUpperCase()=='IMG'&&_hasClass(target,'fl')){
      var uid = target.getAttribute('uid');
      onPicClick(uid);
    }
  }
  function onTabPicDomClick(e){
    var target = e.srcElement?e.srcElement:e.target;
    if(target.tagName.toUpperCase()=='A'&&_hasClass(target,'fold')){      
      foldComments(target);
    }else if(target.tagName.toUpperCase()=='A'&&_hasClass(target,'show_all')){
      displayAllComments(target);
    }else if(target.tagName.toUpperCase()=='A'&&_hasClass(target,'reply')){
      replyUserComments(target);
    }else if(target.tagName.toUpperCase()=='IMG'&&_hasClass(target,'fl')){
      var uid = target.getAttribute('uid');
      onPicClick(uid);
    }
  }
  function onTabShareDomClick(e){
    var target = e.srcElement?e.srcElement:e.target;
    if(target.tagName.toUpperCase()=='IMG'&&_hasClass(target,'fl')){
      var uid = target.getAttribute('uid');
      onPicClick(uid);
    }
  }
  function foldComments(target){
    var ul = target.parentNode.nextSibling;
    var _num = ul.getAttribute('num');    
    if(ul.style.display=="none"){
      ul.style.display="";
      var _ali = getElementsByClassName(ul,'li','textAre');
      var _li1 = _ali[0];
      var _li2 = _ali[1];
      var _mid = getElementsByClassName(ul,'li','allReturn')[0];
      if(_num<3){
        _li1.style.display='none';
        _li2.style.display='';
        var _t = _li2.getElementsByTagName('textarea')[0];
        _t.focus();      
      }else if(_num>=3){
        var _obj = _mid.firstChild;
        displayAllComments(_obj);
        _li1.style.display='none';
        _li2.style.display='';
        var _t = _li2.getElementsByTagName('textarea')[0];
        _t.focus(); 
      }
      target.firstChild.nodeValue="收起回复";
    }else{
      ul.style.display="none";      
      if(_num==0){
        target.firstChild.nodeValue="回复";
      }else if(_num>0){
        target.firstChild.nodeValue=_num+"条回复";
      }else{
        target.firstChild.nodeValue="展开回复";
      }
    }
  }
  function displayAllComments(target){
    var ul = target.parentNode.parentNode;
    var eles = ul.getElementsByTagName('li');
    for(var i=0,len=eles.length-1;i<len;i++){
      eles[i].style.display='';
    }
    target.parentNode.style.display='none';
  }
  /**
   * 转发消息
   * @param {element} target 转发按钮
   */
  function fwdMessage(target){
    var u = target.parentNode;
    var ul = target.parentNode.nextSibling;
    var sid = ul.getAttribute('id');
    var uid = ul.getAttribute('uid');
    var name = u.parentNode.firstChild.firstChild.innerHTML;
    var content = u.parentNode.firstChild.lastChild;
    var children = content.childNodes;
    content = [];
    for(var i=0,length=children.length; i<length; i++) {
      switch(children[i].nodeType) {
        case 3 : content.push(children[i].nodeValue);break;
        case 1 : content.push(handleImg(children[i]));break;
      }
    }
    _removeClass(_gel('user_status_input'),'begin');
    _gel('user_status_input').value='转自'+name+'：'+content.join('');
	  _addClass(_gel('user_status_input_out'),'on');
	  showEmoticon(_gel('user_status_input'));
	  _gel('user_status_input').focus();
	  _gel('textNow').style.display = 'none';
    setFwdId(sid,uid);
  }
  /**
   * 把转发的一些信息设置到输入框上
   * @param {number} sid 状态的id
   * @param {number} uid 发布者id
   */
  function setFwdId(sid,uid){
	_gel('user_status_input').setAttribute('sid',sid);
	_gel('user_status_input').setAttribute('uid',uid);
  }
  /**
   * 回复用户状态
   * @param {element} target 点击的恢复按钮
   */
  function replyUserComments(target){
    var li = target.parentNode.parentNode;
    var ul = li.parentNode;
    var uid = li.getAttribute('id');
    var uname = target.parentNode.firstChild.firstChild.nodeValue;
    var oRe = getElementsByClassName(ul,'li','textAre')[0];
    var oReFull = oRe.nextSibling;
    oReFull.style.display='';
    oRe.style.display='none';
    var oTextArea = oReFull.getElementsByTagName('textarea')[0];
    oTextArea.value = '回复'+uname+'：';
    oTextArea.focus();
    oTextArea.setAttribute('rid',uid);  
  }
  function changeTab(tab){
    closeEmoticon();
    setAllTabClose();
    _addClass(tab,"open");
    _gel(tab.id+'_content').style.display = "block";
    if(oTabSelectCallback[tab.id]){
      oTabSelectCallback[tab.id]();
    }
  }
  function onTabAllSelected(){
    CUR_PAGE = 0;
    TOTAL_NUM = 0;    
    getAllNewsFeeds();
    getPageCount('all');
    startTimer(0);
  }
  function onTabStatusSelected(){
    getStatusFeeds(1);
    startTimer(1);
  }
  function onTabBlogSelected(){
    CUR_PAGE = 0; 
    TOTAL_NUM = 0;    
    getBlogFeeds();
    getPageCount('blog');
    startTimer(2);
  }
  function getPageCount(stype){
    var map = {'all':0,'blog':'20','pic':'30','share':'21,32,33'};    
    XN.Main.apiClient.feed_getFeedList(map[stype],0,50,function(re,ex){
      if(!ex){
        if(re['newsfeed']&&re['newsfeed'].length!=0){
          TOTAL_NUM = re['newsfeed'].length;
          createPage(_gel('tab_'+stype+'_content'),stype,TOTAL_NUM);
        }
      }
    });      
  }
  function createPage(oCon,type,total){
    var nPage = Math.ceil(total/NUM_PER_PAGE);
    if(nPage ==1) return;
    var div = document.createElement('div');
    _setClass(div,'pageBox');    
    for(var i=0;i<nPage;i++){
      var li = document.createElement('a');
      li.href = 'javascript:void(0)';
      li.setAttribute('num',i);
      li.appendChild(document.createTextNode(i+1));
      if(i==CUR_PAGE){
        _setClass(li,'pageOver');
      }
      div.appendChild(li);
    }
    oCon.appendChild(div);
    //addListener
    var cbk = null;
    if(type=='all'){
      cbk = getAllNewsFeeds;
    }else if(type=='blog'){
      cbk = getBlogFeeds;
    }else if(type=='pic'){
      cbk = getPicFeeds;
    }else if(type=='share'){
      cbk = getShareFeeds;
    }
    div.onclick = function(e){
      var e = e?e:window.event;
      var target = e.srcElement?e.srcElement:e.target;
      if(target.tagName.toUpperCase()=='A'){
        if(_hasClass(target,'pageOver')){
          return;
        }else{
          CUR_PAGE = target.getAttribute('num');
          cbk();
        }
      }
    }
  }
  function getBlogFeeds(){
    XN.Main.apiClient.feed_getFeedList('20',CUR_PAGE*NUM_PER_PAGE,NUM_PER_PAGE,function(re,ex){
      if(!ex){
        if(re['newsfeed_total']==0){
          _gel('tab_blog_content').innerHTML = '<div style="text-align:center;">没有日志相关的新鲜事。</div>';
        }else{
          if(re['newsfeed']&&re['newsfeed'].length!=0){
            var feeds = re['newsfeed'];
            var aHtm = [];
            for(var i=0,len=feeds.length;i<len;i++){
              if(oFeedLists[feeds[i]['type']]){
                aHtm.push(oFeedLists[feeds[i]['type']](feeds[i]));
              }
            }
            var sHtm = aHtm.join('');
            _gel('tab_blog_content').innerHTML = sHtm;
            var _con = _gel('tab_blog_content');
            getComments(_con);
            if(CUR_PAGE == 0){
              getPageCount('blog');
            }else{
              createPage(_con,'blog',TOTAL_NUM);
            }
          }else{
            _gel('tab_blog_content').innerHTML = '<div style="text-align:center;">没有日志相关的新鲜事。</div>';
          }
        }
      }else{
        if(ex['userData']['error_code']=='450'){
          window.location.reload(true);
        }
      }
    });
  }
  function onTabPicSelected(){
    CUR_PAGE = 0;
    TOTAL_NUM = 0;    
    getPicFeeds();
    getPageCount('pic');
    startTimer(3);
  }
  function getPicFeeds(){
    XN.Main.apiClient.feed_getFeedList('30',CUR_PAGE*NUM_PER_PAGE,NUM_PER_PAGE,function(re,ex){
      if(!ex){
        if(re['newsfeed_total']==0){
          _gel('tab_pic_content').innerHTML = '<div style="text-align:center;">没有相册相关的新鲜事。</div>';
        }else{
          if(re['newsfeed']&&re['newsfeed'].length!=0){
            var feeds = re['newsfeed'];
            var aHtm = [];
            for(var i=0,len=feeds.length;i<len;i++){
              if(oFeedLists[feeds[i]['type']]){
                aHtm.push(oFeedLists[feeds[i]['type']](feeds[i]));
              }
            }
            var sHtm = aHtm.join('');
            _gel('tab_pic_content').innerHTML = sHtm;
            var _con = _gel('tab_pic_content');
            getComments(_con);
            if(CUR_PAGE == 0){
              getPageCount('pic');
            }else{
              createPage(_con,'pic',TOTAL_NUM);
            }
          }else{
            _gel('tab_pic_content').innerHTML = '<div style="text-align:center;">没有相册相关的新鲜事。</div>';
          }
        }
      }else{
        if(ex['userData']['error_code']=='450'){
          window.location.reload(true);
        }
      }
    });  
  }
  function onTabShareSelected(){
    CUR_PAGE = 0;
    TOTAL_NUM = 0;  
    getShareFeeds();
    getPageCount('share');
    startTimer(4);
  }
  function getShareFeeds(){
    XN.Main.apiClient.feed_getFeedList('21,32,33',CUR_PAGE*NUM_PER_PAGE,NUM_PER_PAGE,function(re,ex){
      if(!ex){
        if(re['newsfeed_total']==0){
          _gel('tab_share_content').innerHTML='<div style="text-align:center;">没有分享相关的新鲜事。</div>';
        }else{
          if(re['newsfeed']&&re['newsfeed'].length!=0){
            var feeds = re['newsfeed'];
            var aHtm = [];
            for(var i=0,len=feeds.length;i<len;i++){
              if(oFeedLists[feeds[i]['type']]){
                aHtm.push(oFeedLists[feeds[i]['type']](feeds[i]));
              }
            }
            var sHtm = aHtm.join('');
            _gel('tab_share_content').innerHTML = sHtm;
            if(CUR_PAGE == 0){
              getPageCount('share');
            }else{
              createPage(_gel('tab_share_content'),'share',TOTAL_NUM);
            }
          }else{
            _gel('tab_share_content').innerHTML='<div style="text-align:center;">没有分享相关的新鲜事。</div>';
          }
        }
      }else{
        if(ex['userData']['error_code']=='450'){
          window.location.reload(true);
        }
      }
    });  
  }
  function setAllTabClose(){
    _removeClass(_gel("tab_all"),"open");
    _removeClass(_gel("tab_status"),"open");
    _removeClass(_gel("tab_pic"),"open");
    _removeClass(_gel("tab_blog"),"open");
    _removeClass(_gel("tab_share"),"open");
    _gel("tab_all_content").style.display = "none";
    _gel("tab_status_content").style.display = "none";
    _gel("tab_pic_content").style.display = "none";
    _gel("tab_blog_content").style.display = "none";
    _gel("tab_share_content").style.display = "none";
  }
  function onLogout() {
    if(timerId){
      clearInterval(timerId);
      timerId = null;
    }    

    XN.Connect.logout(function() {
      _gel('login_page').style.display = '';
      _gel('main_page').style.display = 'none';
      _gel('msgbar').style.display = 'none';
      //清空下面的数据
      _gel('tab_all_content').innerHTML = '';
      _gel('tab_status_content').innerHTML = '';
      _gel('tab_pic_content').innerHTML = '';
      _gel('tab_blog_content').innerHTML = '';
      _gel('tab_share_content').innerHTML = '';
      //清空上头的数据
      _gel('user_status_input').value = '你正在干嘛?';
      _addClass(_gel('user_status_input'),'begin');
      _gel('status_update').innerHTML = '正在读取状态...';
      _gel('status_update').removeAttribute('href');
      _gel('titlebar_username').innerHTML = '';
      _gel('userimg').removeAttribute('src');
      if(_gel('pagination')) {
        _gel('pagination').parentNode.removeChild(_gel('pagination'));
      }
      changeTab(_gel('tab_all'));
      _gel('tab_all_content').innerHTML = '<div class="gg-loading"></div>';
      _gel('tab_status_content').innerHTML = '<div class="gg-loading"></div>';
      _gel('tab_pic_content').innerHTML = '<div class="gg-loading"></div>';
      _gel('tab_blog_content').innerHTML = '<div class="gg-loading"></div>';
      _gel('tab_share_content').innerHTML = '<div class="gg-loading"></div>';
      oUser={
        'id':'',
        'name':'',
        'img':''
      };
      aEmotions = [];
      hasValidation = false;
      //正在编辑的textarea,且打开了表情
      currentTextObj = {};
      //鼠标是否在表情面板里
      inEm = false;
      arthCache = {};
      statusFeeds = {};
      inOnEm = false;
	  isConnectedAlready = false;
      _gel('publisher_emotion').getElementsByTagName('ul')[0].innerHTML = '';
    });
  }
  /**
   * 当登陆成功后，获取用户信息
   */
  function getUserInfo() {
    XN.Main.apiClient.users_getLoggedInUser(function(result, ex) {
      if (!ex) {
        oUser.id = result.uid;
        XN.Main.apiClient.users_getInfo([result.uid], ['name',
          'tinyurl'], function(re, e) {
            if (!e) {
              oUser.name = re[0].name;
              oUser.img = re[0].tinyurl;
              _gel('titlebar_username').innerHTML = re[0].name;
              _gel('userimg').src = re[0].tinyurl;
              _gel('userimg').onclick = function(){
                onPicClick(re[0].uid);
              }
              getStatus(handleMyStatus);
              _gel('status_update').href = 'http://status.renren.com/getdoing.do?id='+oUser['id'];
            }
          });
        getAllEmotions(getAllNewsFeeds);        
      }
    })
  }
  /**
   * 得到所有的表情，并进行转义
   * @param {function} cbk 当发生错误时执行
   */
  function getAllEmotions(cbk){
    XN.Main.apiClient.status_getEmoticons('all', function(result,
      ex) {
      if (!ex) {
        cbk();
        aEmotions = result;
        for (var i = 0, length = aEmotions.length; i < length; i++) {
          aEmotions[i]['emotion'] = aEmotions[i]['emotion']
          .replace(/\\/ig, '\\\\');
          aEmotions[i]['emotion'] = aEmotions[i]['emotion']
          .replace(/\$/ig, '\\\$');
          aEmotions[i]['emotion'] = aEmotions[i]['emotion']
          .replace(/\^/ig, '\\\^');
          aEmotions[i]['emotion'] = aEmotions[i]['emotion']
          .replace(/\*/ig, '\\\*');
          aEmotions[i]['emotion'] = aEmotions[i]['emotion']
          .replace(/\./ig, '\\\.');
          aEmotions[i]['emotion'] = aEmotions[i]['emotion']
          .replace(/\+/ig, '\\\+');
          aEmotions[i]['emotion'] = aEmotions[i]['emotion']
          .replace(/\?/ig, '\\\?');
          aEmotions[i]['emotion'] = aEmotions[i]['emotion']
          .replace(/\=/ig, '\\\=');
          aEmotions[i]['emotion'] = aEmotions[i]['emotion']
          .replace(/\!/ig, '\\\!');
          aEmotions[i]['emotion'] = aEmotions[i]['emotion']
          .replace(/\|/ig, '\\\|');
          aEmotions[i]['emotion'] = aEmotions[i]['emotion']
          .replace(/\//ig, '\\\/');
          aEmotions[i]['emotion'] = aEmotions[i]['emotion']
          .replace(/\(/ig, '\\\(');
          aEmotions[i]['emotion'] = aEmotions[i]['emotion']
          .replace(/\)/ig, '\\\)');
          aEmotions[i]['emotion'] = aEmotions[i]['emotion']
          .replace(/\[/ig, '\\\[');
          aEmotions[i]['emotion'] = aEmotions[i]['emotion']
          .replace(/\]/ig, '\\\]');
          aEmotions[i]['emotion'] = aEmotions[i]['emotion']
          .replace(/\{/ig, '\\\{');
          aEmotions[i]['emotion'] = aEmotions[i]['emotion']
          .replace(/\}/ig, '\\\}');
        }
      }else{
        cbk();
      }
    });    
  }
  var oFeedLists={
    "10":function(obj){return onStatusItemCreate(obj);},    
    "20":function(obj){return onBlogItemCreate(obj,true);},
    "21":function(obj){return onBlogItemCreate(obj,false);},
    "30":function(obj){return onPicItemCreate(obj,true);},
    "32":function(obj){return onPicItemCreate(obj,false);},
    "33":function(obj){return onPicItemCreate(obj,false,true);}
  }
  
  function getAllNewsFeeds(){
    XN.Main.apiClient.feed_getFeedList(0,CUR_PAGE*NUM_PER_PAGE,NUM_PER_PAGE,function(re,ex){
      if(!ex){
        if(re['newsfeed_total']==0){
          _gel('tab_all_content').innerHTML = '<div style="text-align:center;">当你的朋友发表日志、照片或者帖子，这里会有提示。</div>';
        }else{
          if(re['newsfeed']&&re['newsfeed'].length!=0){
            _gel('mainpage').style.display='';
            _gel('permissionpage').style.display='none';
            hasValidation=true;
            var feeds = re['newsfeed'];
            var aHtm = [];
            for(var i=0,len=feeds.length;i<len;i++){
              if(oFeedLists[feeds[i]['type']]){
                aHtm.push(oFeedLists[feeds[i]['type']](feeds[i]));
              }
            }
            var sHtm = aHtm.join('');
            _gel('tab_all_content').innerHTML = sHtm;
            var _con = _gel('tab_all_content');
            getComments(_con);
            if(CUR_PAGE == 0){
              getPageCount('all');
            }else{
              createPage(_con,'all',TOTAL_NUM);
            }
          }else{
            _gel('tab_all_content').innerHTML = '<div style="text-align:center;">当你的朋友发表日志、照片或者帖子，这里会有提示。</div>';
          }
        }
      }else{      
        if(ex['userData']['error_code']=='450'){
          window.location.reload(true);
        }else if(ex['userData']['error_code']=='20204'){      
          _gel('mainpage').style.display='none';
          _gel('permissionpage').style.display='';
          hasValidation=false;
        }
      }
    });
  
  }
  var oCommentLists={
    "10":function(obj){onStatusCommentCreate(obj);},    
    "20":function(obj){onBlogCommentCreate(obj);},
    "30":function(obj){onPicCommentCreate(obj);}
  }
  function getComments(con){
    var eles = con.getElementsByTagName('ul');
    for(var i=0,len=eles.length;i<len;i++){
      var type = eles[i]['type'] || eles[i].getAttribute('type');
      if(oCommentLists[type]){
        oCommentLists[type](eles[i]);
      }
    }
  }
  function onStatusCommentCreate(con,_showAll){
    var aHtm=[];
    var num = con.getAttribute('num');
    var id = con.getAttribute('id');
    var uid= con.getAttribute('uid');
    if(num==0||!num){
      aHtm.push(createTopIconList());
      aHtm.push(createReplyList(oUser.img));
      var sHtm = aHtm.join('');
      con.innerHTML = sHtm;
      addReplyListener(con,'10');
    }else{
      XN.Main.apiClient.status_getComment(id,uid,num,function(result,ex){
        onStatusCommentCbk(result,ex,con,_showAll);
      });
    }
  }
  function onStatusCommentCbk(result,ex,con,_showAll){
    if(!ex){
      var aHtm=[];
      var len = result.length;
      if(len<3){
        aHtm.push(createReplyList(oUser.img));
        for(var i=0;i<len;i++){
          aHtm.push(createContentList(result[i]['tinyurl'],result[i]['name'],result[i]['time'],handleMsg(result[i]['text'],true),result[i]['uid'],true));
        }
        aHtm.push(createTopIconList());
      }else{
        if(_showAll){
          aHtm.push(createReplyList(oUser.img));
          for(var i=0;i<len;i++){
            aHtm.push(createContentList(result[i]['tinyurl'],result[i]['name'],result[i]['time'],handleMsg(result[i]['text'],true),result[i]['uid'],true));
          }
          aHtm.push(createTopIconList()); 
        }else{
          aHtm.push(createReplyList(oUser.img));
          for(var i=0;i<len;i++){
            if(i==0){
              aHtm.push(createContentList(result[i]['tinyurl'],result[i]['name'],result[i]['time'],handleMsg(result[i]['text'],true),result[i]['uid'],true));
            }else if(i==len-1){
              aHtm.push(createShowAllList(len));
              aHtm.push(createContentList(result[i]['tinyurl'],result[i]['name'],result[i]['time'],handleMsg(result[i]['text'],true),result[i]['uid'],true));
            }else{
              aHtm.push(createContentList(result[i]['tinyurl'],result[i]['name'],result[i]['time'],handleMsg(result[i]['text'],true),result[i]['uid'],false));
            }
          }
          aHtm.push(createTopIconList()); 
        }
      }
      aHtm.reverse();
      var sHtm = aHtm.join('');
      if(con){
        con.innerHTML = sHtm;
        addReplyListener(con,'10');
      }
    }
  }
  function onBlogCommentCreate(con,_showAll){
    var id = con.getAttribute('id');
    var uid= con.getAttribute('uid');
    XN.Main.apiClient.blog_getComments(id,uid,1,50,function(result,ex){
      onBlogCommentCbk(result,ex,con,_showAll);
    });
  }
  function onBlogCommentCbk(re,e,oCon,_showAll){
    var aHtm=[];
    var len = re.length;
    if(oCon){
      oCon.setAttribute('num',len);
    }else{
      return;
    }
    if(!e){
      if(len==0){
        aHtm.push(createTopIconList());
        aHtm.push(createReplyList(oUser.img));
        var sHtm = aHtm.join('');
        if(oCon){
          oCon.innerHTML = sHtm;
          addReplyListener(oCon,'20');
        }
        return;
      }else if(len<3){
        aHtm.push(createReplyList(oUser.img));
        for(var i=0;i<len;i++){
          aHtm.push(createContentList(re[i]['headurl'],re[i]['name'],re[i]['time'],handleMsg(re[i]['content'],true),re[i]['uid'],true));
        }
        aHtm.push(createTopIconList());
      }else{
        if(_showAll){
          aHtm.push(createReplyList(oUser.img));
          for(var i=0;i<len;i++){
            aHtm.push(createContentList(re[i]['headurl'],re[i]['name'],re[i]['time'],handleMsg(re[i]['content'],true),re[i]['uid'],true));
          }
        }else{
          aHtm.push(createReplyList(oUser.img));
          for(var i=0;i<len;i++){
            if(i==0){
              aHtm.push(createContentList(re[i]['headurl'],re[i]['name'],re[i]['time'],handleMsg(re[i]['content'],true),re[i]['uid'],true));
            }else if(i==len-1){
              aHtm.push(createShowAllList(len));
              aHtm.push(createContentList(re[i]['headurl'],re[i]['name'],re[i]['time'],handleMsg(re[i]['content'],true),re[i]['uid'],true));
            }else{
              aHtm.push(createContentList(re[i]['headurl'],re[i]['name'],re[i]['time'],handleMsg(re[i]['content'],true),re[i]['uid'],false));
            }
          }
          aHtm.push(createTopIconList()); 
        }
      }
      aHtm.reverse();
      var sHtm = aHtm.join('');
      oCon.innerHTML = sHtm;
      addReplyListener(oCon,'20');
    }
  }
  function onPicCommentCreate(con,_showAll){
    var pid = con.getAttribute('id');
    var uid= con.getAttribute('uid');
    XN.Main.apiClient.photos_getComments(uid,pid,function(result,ex){
      onPicCommentCbk(result,ex,con,_showAll);
    });
  }
  function onPicCommentCbk(re,e,oCon,_showAll){
    var aHtm=[];
    var len = re.length;
    if(oCon){
      oCon.setAttribute('num',len);
    }else{
      return;
    }
    if(!e){
      if(len==0){
        aHtm.push(createTopIconList());
        aHtm.push(createReplyList(oUser.img));
        var sHtm = aHtm.join('');
        oCon.innerHTML = sHtm;
        addReplyListener(oCon,'30');
        return;
      }else if(len<3){
        aHtm.push(createTopIconList());
        for(var i=0;i<len;i++){
          aHtm.push(createContentList(re[i]['headurl'],re[i]['name'],re[i]['time'],re[i]['text'],re[i]['uid'],true));
        }
        aHtm.push(createReplyList(oUser.img));
      }else{
        if(_showAll){
          aHtm.push(createTopIconList());
          for(var i=0;i<len;i++){
            aHtm.push(createContentList(re[i]['headurl'],re[i]['name'],re[i]['time'],re[i]['text'],re[i]['uid'],true));
          }
        }else{
          aHtm.push(createTopIconList());
          for(var i=0;i<len;i++){
            if(i==0){
              aHtm.push(createContentList(re[i]['headurl'],re[i]['name'],re[i]['time'],re[i]['text'],re[i]['uid'],true));
            }else if(i==len-1){
              aHtm.push(createShowAllList(len));
              aHtm.push(createContentList(re[i]['headurl'],re[i]['name'],re[i]['time'],re[i]['text'],re[i]['uid'],true));
            }else{
              aHtm.push(createContentList(re[i]['headurl'],re[i]['name'],re[i]['time'],re[i]['text'],re[i]['uid'],false));
            }
          }          
        }
        aHtm.push(createReplyList(oUser.img));
      }
      var sHtm = aHtm.join('');
      oCon.innerHTML = sHtm;
      addReplyListener(oCon,'30');
    }
  }
  function addReplyListener(con,type){
    var eles = con.getElementsByTagName('textarea');
    var oRe1 = eles[0];
    var oRe2 = eles[1];
    oSubmitDiv = oRe2.parentNode.parentNode.nextSibling;
    var btn = getElementsByClassName(oSubmitDiv,'input','btn')[0];
    var oFaceBtn = oSubmitDiv.firstChild;
    var bOnFaceBtn=false;
    oRe1.onclick = function(){
      oRe1.parentNode.parentNode.parentNode.style.display='none';      
      oRe2.parentNode.parentNode.parentNode.style.display='';
      oRe2['rid'] = con['id'];
      oRe2.focus();
    }
    oRe2.onblur = function(){
      if(bOnFaceBtn==true){
      
      }else{
        setTimeout(function(){
          if(!_trim(oRe2.value)){
            oRe1.parentNode.parentNode.parentNode.style.display='';
            oRe2.parentNode.parentNode.parentNode.style.display='none';
            closeEmoticon();  
          }
        },300);
        bIsOnEdit = false;
      }
    }
    oRe2.onfocus = function(){
      setTimeout(function(){
        countText(oRe2,btn.nextSibling,140);
      },100);
      bIsOnEdit = true;
    }
    //full size reply box 
    btn.onclick = function(){
      var li=btn.parentNode.parentNode;
      var ul = li.parentNode;
      var textarea = li.getElementsByTagName('textarea')[0];
      var text = textarea.value;

      if(_trim(text)==''){
        return false;
      }
      var rid = textarea.getAttribute('rid');
      var id = ul.getAttribute('id');
      var uid = ul.getAttribute('uid');
      var type = ul.getAttribute('type');
      _addClass(oRe2,'text-disable');
      oRe2.blur();
      replyComments(type,id,uid,text,rid,ul);
      closeEmoticon();
      bIsOnEdit = false;
    }
    //count input text
    oRe2.onkeydown = function(e){
      e=e?e:window.event;
      var keycode = e.keyCode||e.which||e.charCode;
      if(keycode==13){
        var li=btn.parentNode.parentNode;
        var ul = li.parentNode;
        var textarea = li.getElementsByTagName('textarea')[0];
        var text = textarea.value;
        if(_trim(text)==''){
          return false;
        }
        var rid = textarea.getAttribute('rid');
        var id = ul.getAttribute('id');
        var uid = ul.getAttribute('uid');
        var type = ul.getAttribute('type');
        _addClass(oRe2,'text-disable');
        oRe2.blur();
        replyComments(type,id,uid,text,rid,ul);
        closeEmoticon();
        bIsOnEdit = false;
        return false;
      }else{
        countText(oRe2,btn.nextSibling,140);
      }
    }
    oRe2.onkeyup = function(e){
      e=e?e:window.event;
      var keycode = e.keyCode||e.which||e.charCode;
      if(keycode==13){
        closeEmoticon();
        return false;
      }else{
        countText(oRe2,btn.nextSibling,140);
      }
    }
    oFaceBtn.onmouseover = function(){
      bOnFaceBtn = true;
    }
    oFaceBtn.onmouseout = function(){
      bOnFaceBtn = false;
    }
    oFaceBtn.onclick = function(){
      showEmoticon(oRe2,true);
      oRe2.focus();
      bOnFaceBtn = false;
    }
  }
  function replyComments(type,id,uid,text,rid,con){
    if(type=='10'){
      XN.Main.apiClient.status_addComment(id,uid,text,rid,function(re,e){
        if(!e){
          var num = parseInt(con.getAttribute('num'),10)+1;
          con.setAttribute('num',num);
          onStatusCommentCreate(con,true);
        }else{
          var _ali = getElementsByClassName(con,'li','textAre');
          var _li1 = _ali[0];
          var _li2 = _ali[1];
          var _t = _li2.getElementsByTagName('textarea')[0];
          _removeClass(_t,'text-disable');
          _t.value ='';
          _t.blur();
          _li1.style.display='';
          _li2.style.display='none';
          dealEx(e);
        }
      });
    }else if(type=='20'){
      XN.Main.apiClient.blog_addComment(id,uid,text,0,rid,function(re,e){
        if(!e){
          var num = parseInt(con.getAttribute('num'),10)+1;
          con.setAttribute('num',num);
          onBlogCommentCreate(con,true);
        }else{
          var _ali = getElementsByClassName(con,'li','textAre');
          var _li1 = _ali[0];
          var _li2 = _ali[1];
          var _t = _li2.getElementsByTagName('textarea')[0];
          _removeClass(_t,'text-disable');
          _t.value ='';
          _li1.style.display='';
          _li2.style.display='none';
          dealEx(e);       
        }
      });
    }else if(type=='30'){
      XN.Main.apiClient.photos_addComment(uid,id,text,rid,0,function(re,e){
        if(!e){
          var _ali = getElementsByClassName(con,'li','textAre');
          var _li1 = _ali[0];
          var _li2 = _ali[1];
          var _t = _li2.getElementsByTagName('textarea')[0];
          _removeClass(_t,'text-disable');
          _t.value ='';
          _li1.style.display='';
          _li2.style.display='none';
          var num = parseInt(con.getAttribute('num'),10)+1;
          con.setAttribute('num',num);
          onPicCommentCreate(con,true);
        }else{
          dealEx(e);
        }
      });
    }
  }
  function dealEx(e){
    if(e['userData']['error_code']=='20213'){
      _gel('mainpage').style.display='none';
      _gel('permissionpage').style.display='';
      hasValidation=false;
    }else if(e['userData']['error_code']=='10400'){
      showPopUp(e['userData']['error_msg']);
    }else if(e['userData']['error_code']=='10402'){
      showPopUp(e['userData']['error_msg']);
    }else{
      showPopUp('未知错误，发送失败。');
    }
    
  }
  function countText(oField,oShowCon,nLimit){
		if (oField.value.length > nLimit){
			// if too long...trim it!
			oField.value = oField.value.substring(0, nLimit);
			oShowCon.firstChild.nodeValue = nLimit+'/'+nLimit;
			// otherwise, update 'characters left' counter
		}else{
			oShowCon.firstChild.nodeValue = oField.value.length+'/'+nLimit;
		}
  }
  function createTopIconList(){
    return '<li class="icon1"></li>';
  }
  function createShowAllList(num){
    var str = '<li class="allReturn">'
            + '<a href="javascript:void(0);" class="show_all">显示全部'
            + num+'条</a></li>';
    return str;
  }
  function createContentList(imgsrc,name,time,text,uid,isDisplay){
    if(!imgsrc){
      imgsrc='img/no_pic.png';
    }
    var sReply = '<a href="javascript:void(0);" class="reply"> 回复</a>';
    if(uid==oUser['id']){
      sReply='';
    }
    if(isDisplay){
      var display = '';
    }else{
      var display = 'display:none';
    }
    var str = '<li id='+uid+' style="'+display+'">'
            + '<img height="30" width="30" align="left" class="fl" '
            + 'src='+imgsrc+' uid='+uid+ ' />'            
            + '<div class="items"><a class="font1" target="_blank" href="'
            + 'http://renren.com/profile.do?id='+uid+'">'
            + name+'</a>  <span class="font2 fontSmall">'
            + time+'</span><br/>'
            + text
            + sReply
            + '</div></li>';
    return str;
  }
  /**
   * 生成回复栏
   * @param {string} imgsrc 头像地址
   */
  function createReplyList(imgsrc){
    if(!imgsrc){
      imgsrc='img/no_pic.png';
    }
    var str = '<li class="textAre"><div class="textAreBox">'
            + '<fieldset><textarea class="reviewArea begin" name="textarea" >添加回复</textarea></fieldset>'
            + '</div></li>'
            + '<li class="textAre over" style="display:none"><div class="textAreBox">'
            + '<img height="30" width="30" class="fl mR6" src='
            + imgsrc +' />'
            + '<fieldset><textarea class="reviewArea fl" name="textarea"></textarea></fieldset></div>'
            + '<div class="submitBtnBox">'
            + '<a class="face_re">表情</a>'
            + '<input type="button" class="btn" value="回复"/>'
            + '<span class="font2">0/140</span>'
            + '</div></li>';
    return str;  
  }
  /**
   * 创建一个状态
   * @param {object} oItem 一个状态类
   */
  function onStatusItemCreate(oItem){
    var sTime = parseTime(parseTimeStr2(oItem['time']),true);
    var sName = oItem['from'][0]['name'];
    var uid = oItem['from'][0]['id'];
    var sContent = handleMsg(oItem['content'],true);
    var sHeadUrl = oItem['from'][0]['headurl'];
    var str = '<div class="item" id='+oItem['id']+' uid='+uid+'>'
            + '<img height="30" width="30" class="fl" src='+sHeadUrl+' uid='
            + uid+' />'
            + '<a href="javascript:void(0)" class="del"></a>'
            + '<div class="itemContent"><h3 class="itemT">'
            + '<a class="font1" href="http://renren.com/profile.do?id='
            + uid+'" target="_blank">'
            + sName+'</a>：<span>'
            + sContent +'</span></h3>'
            + '<div class="timeText"><img class="talk" src="img/a.gif"/> '
            + '<span class="font2">'+sTime+'</span>  '
            + '<a href="javascript:void(0);" class="fold">收起回复</a> '
            + '<span class="font1">|</span> '
            + '<a href="javascript:void(0);" class="fwd">转发</a></div>'
            + '<ul type='+oItem['type']+' num='
            + oItem['reply_count']+' id='+oItem['id']+' uid='
            + uid+'></ul>'
            + '</div></div>';
    return str;
  }
  function onBlogItemCreate(oItem,isOwn){
    var sTime = parseTime(parseTimeStr2(oItem['time']),true);
    var sName = oItem['from'][0]['name'];
    var uid = oItem['from'][0]['id'];
    var sHeadUrl = oItem['from'][0]['headurl'];
    var sRe = '';
    if(isOwn){
      var sTitle = '发布日志 <a class="font1" target="_blank" href="http://blog.renren.com/GetEntry.do?id='+oItem['id']
                 +'&owner='+oItem['from'][0]['id']+'">'
                 +oItem['title']+'</a>';
      sRe = '<a href="javascript:void(0);" class="fold">收起回复</a>';
    }else{
      var sTitle = '分享<a class="font1" target="_blank" href="http://renren.com/profile.do?id='            
                 + oItem['friend'][0]['id']+'">'
                 +oItem['friend'][0]['name']+'</a>'
                 + '的日志<a class="font1" target="_blank" href="http://blog.renren.com/GetEntry.do?id='+oItem['id']
                 +'&owner='+oItem['friend'][0]['id']+'">'
                 +oItem['title']+'</a>';
    }
    var sContent = handleMsg(oItem['description'],true);
    var str = '<div class="item">'
            + '<img height="30" width="30" class="fl" src='+sHeadUrl+' uid='
            + uid+' />'
            + '<a href="javascript:void(0)" class="del"></a>'
            + '<div class="itemContent"><h3 class="itemT">'
            + '<a class="font1" target="_blank" href="http://renren.com/profile.do?id='            + uid+'">'
            + sName+'</a> '
            + sTitle+' <br/></h3>'
            + '<div class="photoBox lineH22 font2">'
            + sContent+ '</div>'
            + '<div class="timeText"><img class="blog" src="img/a.gif"/> '
            + '<span class="font2">'+sTime+'</span>  '
            + sRe            
            + '</div>'+ '<ul type='+oItem['type']+' id='+oItem['id']+' uid='
            + uid+'></ul>'
            + '</div></div>';
    return str;
  }
  function onPicItemCreate(oItem,isOwn,isAlbum){
    var sTime = parseTime(parseTimeStr2(oItem['time']),true);
    var sName = oItem['from'][0]['name'];
    var uid = oItem['from'][0]['id'];
    var sHeadUrl = oItem['from'][0]['headurl'];
    var sNum = oItem['pic_count'];
    var sAlbum = oItem['album_name'];
    var sRe = '';
    if(isOwn){
      var sTitle = '上传了'+sNum+'张照片至 <a class="font1" target="_blank" href="http://photo.renren.com/getalbum.do?id='
                 + oItem['id']+'&owner='+uid+'">'
                 + sAlbum+'</a>';
      sRe = '<a href="javascript:void(0);" class="fold">收起回复</a>';
      
      var aPicSrc = oItem['pic_src'];
      var sPicSrc1 = 'http://xnimg.connect.renren.com/app_full_proxy.do?src='
                   + encodeURIComponent(aPicSrc[0]);
      var sImg = '<a class="mLR2 fl" target="_blank" href="http://photo.renren.com/getalbum.do?id='
                   + oItem['id']+'&owner='+uid+'"><img src='+sPicSrc1+' /></a>';
      if(aPicSrc.length>1){
        if(isAlbum){
          sImg += '<span class="font2">共'+aPicSrc.length+'张图片</span>';
        }else{ 
          var sPicSrc2 = 'http://xnimg.connect.renren.com/app_full_proxy.do?src='
                       + encodeURIComponent(aPicSrc[1]);      
          sImg += '<a class="mLR2 fl" target="_blank" href="http://photo.renren.com/getalbum.do?id='
                   + oItem['id']+'&owner='+uid+'"><img src='+sPicSrc2+' /></a>';
        }
      }      
      
    }else{
      if(isAlbum){
        var sTitle = '分享<a class="font1" target="_blank" href="http://renren.com/profile.do?id='            
                   + oItem['friend'][0]['id']+'">'
                   + oItem['friend'][0]['name']
                   + '</a>的相册<a class="font1" target="_blank" href="http://photo.renren.com/getalbum.do?id='
                   + oItem['id']+'&owner='+oItem['friend'][0]['id']+'">'
                   + sAlbum+'</a>';
      }else{
        var sTitle = '分享<a class="font1" target="_blank" href="http://renren.com/profile.do?id='            
                   + oItem['friend'][0]['id']+'">'
                   + oItem['friend'][0]['name']
                   + '</a>的照片<a class="font1" target="_blank" href="http://photo.renren.com/getalbum.do?id='
                   + oItem['id']+'&owner='+oItem['friend'][0]['id']+'">'
                   + sAlbum+'</a>';
      }
      var aPicSrc = oItem['pic_src'];
      var sPicSrc1 = 'http://xnimg.connect.renren.com/app_full_proxy.do?src='
                   + encodeURIComponent(aPicSrc[0]);
      var sImg = '<a class="mLR2 fl" target="_blank" href="http://photo.renren.com/getalbum.do?id='
                   + oItem['id']+'&owner='+oItem['friend'][0]['id']+'"><img src='+sPicSrc1+' /></a>';
      if(aPicSrc.length>1){
        if(isAlbum){
          sImg += '<span class="font2">共'+aPicSrc.length+'张图片</span>';
        }else{ 
          var sPicSrc2 = 'http://xnimg.connect.renren.com/app_full_proxy.do?src='
                       + encodeURIComponent(aPicSrc[1]);      
          sImg += '<a class="mLR2 fl" target="_blank" href="http://photo.renren.com/getalbum.do?id='
                   + oItem['id']+'&owner='+oItem['friend'][0]['id']+'"><img src='+sPicSrc2+' /></a>';
        }
      }
    }

    var str = '<div class="item">'
            + '<img height="30" width="30" class="fl" src='+sHeadUrl+' uid='
            + uid+' />'
            + '<a href="javascript:void(0)" class="del"></a>'
            + '<div class="itemContent">'
            + '<h3 class="itemT">'
            + '<a class="font1" target="_blank" href="http://renren.com/profile.do?id='            + uid+'">'
            + sName+'</a>：'
            + sTitle+'</h3>'
            + '<div class="photoBox gpic">'
            + sImg+'</div>'
            + '<div class="timeText">'
            + '<img class="pic" src="img/a.gif"/> '
            + '<span class="font2">'+sTime+'</span>  '
            + sRe
            + '</div>'+ '<ul type='+oItem['type']+' id='+oItem['pic_id']+' uid='
            + uid+'></ul>'
            + '</div></div>';
    return str;
  }

  function onPicClick(uid) {
    window.open("http://renren.com/profile.do?id=" + uid);
  }
  
  /**
   * 获得新鲜事的订阅
   * @param {number} page_num 当前页数
   * @param {boolean} nofresh 是否发送请求
   */
  function getStatusFeeds(page_num,nofresh) {
  if(typeof page_num != 'number') {
    page_num = parseInt(page_num.innerHTML);
  }
  if(nofresh) {
    connect_getStatusFeeds(page_num,StatusFeedsPages);
  } else {
    XN.Main.apiClient.feed_getFeedList('10',page_num,50,function(reTest,exTest){
      if(!exTest) {
        if(!reTest.newsfeed) {
          _gel('tab_status_content').innerHTML = '<div style="text-align:center">没有状态相关的新鲜事。</div>';
          return;
        }
        if(reTest.newsfeed.length == 0) {
          _gel('tab_status_content').innerHTML = '<div style="text-align:center">没有状态相关的新鲜事。</div>';
        } else {
          StatusFeedsPages = getPageDiv(reTest.newsfeed.length,page_num,function(ele){
                          getStatusFeeds(ele,true);
                          _gel('tab_status_content').innerHTML = '<div class="gg-loading"></div>';
                        });
          if(!StatusFeedsPages) {
            getStatusFeeds(1);
            return;
          } else {
            connect_getStatusFeeds(page_num,StatusFeedsPages);
          }
        }
      } else {
          if(exTest['userData']['error_code']=='450'){
            window.location.reload(true);
          }else if(exTest['userData']['error_code']=='20204'){
            _gel('mainpage').style.display='none';
            _gel('permissionpage').style.display='';
            hasValidation=false;
          }
      }
    });
  }

  }
  
  function connect_getStatusFeeds(page_num,StatusFeedsPages) {
    XN.Main.apiClient.connect_getStatusFeeds(page_num, NUM_PER_PAGE, function(result, ex) {
    if (!ex) {
      _gel('mainpage').style.display='';
      _gel('permissionpage').style.display='none';
      hasValidation=true;
      statusFeeds = result;
      var feeds = [];
      var status = result.status;
      var profiles = result.profiles;
      if(!status.length && !profiles.length) {
        _gel('tab_status_content').innerHTML = '<div style="text-align:center">没有状态相关的新鲜事。</div>';
        return;
      }
      for (var i = 0, len = status.length; i < len; i++) {
        var uid = status[i].uid;
        var user = getProfile(uid, profiles);
        var item = {
          'sid' : status[i].status_id,
          'uid' : uid,
          'username' : user.name,
          'userpic' : user.tinyurl,
          'msg' : status[i].message,
          'time' : status[i].time,
          're_num' : status[i].comment_count
        };
        if (status[i].comment_list) {
          item.re = status[i].comment_list;
        }
        feeds.push(item);
      }
      if (feeds.length > 0) {
        _gel('tab_status_content').innerHTML = '';
        //var ol = document.createElement('ol');
        for (var i = 0, len = feeds.length; i < len; i++) {
          //var li = createList(feeds[i]);
          _gel('tab_status_content').appendChild(createList(feeds[i]));
        }
        //_gel('tab_status_content').appendChild(ol);
      }
      if(StatusFeedsPages) {
        _gel('contentAll').appendChild(StatusFeedsPages);
        _gel('pagination').style.display = '';
      }
      //_gel('tab_status_content').parentNode.insertBefore(pageEle,_gel('tab_status_content'));
    } else {
      if(ex['userData']['error_code']=='450'){
        window.location.reload(true);
      }else if(ex['userData']['error_code']=='20204'){
        _gel('mainpage').style.display='none';
        _gel('permissionpage').style.display='';
        hasValidation=false;
      }
    }
  });
  }
  function startTimer(tabIndex){
    var pagination = _gel('pagination');
    if(timerId){
      clearInterval(timerId);
      timerId = null;
    }
    var timerFunc = null;
    if(tabIndex==0){
      timerFunc = function(){
      if(!bIsOnEdit){
        getAllNewsFeeds();
        getEvents();
      }
      }
    }else if(tabIndex==1){
      timerFunc = function(){
      if(!bIsOnEdit){
        if(!pagination) {
          getStatusFeeds(1);
        } else {
          var ch = _gel('pagination').childNodes;
          for(var i=0; ch[i]; i++) {
           if(_hasClass(ch[i],'pageOver')) {
             getStatusFeeds(ch[i]);
             getEvents();
             break;
            }
           }
        }
      }
      }      
    }else if(tabIndex==2){
      timerFunc = function(){
      if(!bIsOnEdit){
        getBlogFeeds();
        getEvents();
      }
      }        
    }else if(tabIndex==3){
      timerFunc = function(){
      if(!bIsOnEdit){
        getPicFeeds();
        getEvents();
      }
      }      
    }else if(tabIndex==4){
      timerFunc = function(){
      if(!bIsOnEdit){
        getShareFeeds();
        getEvents();
      }
      }      
    }else{
      timerFunc = null;
    }
    if(timerFunc){
      timerId = setInterval(timerFunc,timeInterval);
    }
  }
  /**
   * 创建回复显示
   * @param {object} obj 回复的内容
   */
  function createList(obj) {
    var li = document.createElement('div');
    li.className = "item";
    li.setAttribute('sid', obj.sid);
    li.setAttribute('uid', obj.uid);
    var stime = parseTime(obj.time);
    var re = 'none', re_div = '';
    if (obj.re_num == 1) {
      re = '';
      var comment = obj.re[0];
      var uid = comment.uid;
      var user = getProfile(uid, statusFeeds.profiles);
      re_div = createItem(user,comment,obj);
    } else if (obj.re_num == 2) {
      re = '';
      var comment = obj.re[0];
      var uid = comment.uid;
      var user = getProfile(uid, statusFeeds.profiles);
      var comment2 = obj.re[1];
      var uid2 = comment2.uid;
      var user2 = getProfile(uid2, statusFeeds.profiles);
      re_div = createItem(user,comment,obj);
      re_div += createItem(user2,comment2,obj);
    } else if (obj.re_num > 2) {
      re = '';
      var comment = obj.re[0];
      var uid = comment.uid;
      var user = getProfile(uid, statusFeeds.profiles);
      var comment2 = obj.re[1];
      var uid2 = comment2.uid;
      var user2 = getProfile(uid2, statusFeeds.profiles);
      re_div = createItem(user,comment,obj);
      re_div += createMidItem(obj);
      re_div += createItem(user2,comment2,obj);
    }

    li.innerHTML = '<img width="30" height="30" class="fl" src="'
    + obj.userpic
    + '" name="'
    + obj.uid
    + '"/><div class="itemContent">'
    + '<h3 class="itemT">'
    + '<a target="_blank" href="http://renren.com/profile.do?id='
    + obj.uid
    + '" class="font1">'
    + obj.username
    + '</a>：<span>'
    + obj.msg
    + '</span></h3><div class="timeText">'
    + '<img class="talk" src="img/a.gif"/>&nbsp;'
    + '<span class="font2">'
    + stime
    + '</span>'
    + '&nbsp;<a class="collapse funt1" count='
	+ obj.re_num
	+ '>收起回复</a><span class="font1">&nbsp;|&nbsp;</span>'
    + '<a href="javascript:void(0)" class="fwd" uid='
    + obj.uid
    + ' >转发</a></div>'
    + '<ul><li class="icon1"></li>'
    + re_div
	+ '<li class="textAre"><div class="textAreBox">'
	+ '<img width="30" height="30" class="fl mR6" src="'
	+ oUser.img
	+'"/>'
	+ '<fieldset><textarea class="reviewArea fl begin" sid="'
	+ obj.sid
	+ '" uid="'
	+ obj.uid
	+ '" name="textarea">添加回复</textarea></fieldset>'
	+ '</div><div class="submitBtnBox"><a class="face_re">表情</a>'
	+ '<input type="button" class="btn" value="回复"/><span class="font2 counter">0</span><span class="font2">/140</span>'
	+ '</div></li>'
    + '</ul></div>';
	var as = li.getElementsByTagName('a');
	for(var num=0; as[num]; num++) {
		if(_hasClass(as[num],'face_re')) {
			as = as[num];
			break;
		}
	}
	as.onmouseover = onEmo(true);
	as.onmouseout = onEmo(false);
    return li;
  }
  
  function onEmo(struts) {
	return function() {
		inOnEm = struts;
	}
  }
  /**
   * 创建一条回复
   * @param {object} user 发表的用户
   * @param {object} comment 相关的信息
   * @param {object} obj 未使用,废弃
   */
  function createItem(user,comment,obj){
    var sContent = '<li>'
    + '<img width="30" height="30" align="left" class="fl" src="'
    + user.tinyurl
    + '" name="'
    + user.uid
    + '"></img>'
    + '<div class="items"><a target="_blank" href="http://renren.com/profile.do?id='
    + user.uid + '" class="font1">' + user.name + '</a>'
    + '<span class="font2 fontSmall">&nbsp;' + comment.time + '</span><br/>'
    + comment.cont;
    if (user.uid == oUser.id) {
      sContent += '</div></li>';
    } else {
      sContent += '<a class="font3 cu replay" name="'
	  + user.name
	  + '" uid="'
      + user.uid
      + '" href="javascript:void(0)">回复</a></div></li>';
    }
    return sContent;
  }
  /**
   * 创建中间的现实X条信息
   */
  function createMidItem(obj){
    var sContent = '<li class="allReturn">'
    + '<a href="javascript:void(0)" num='
    + obj.re_num
    + '>显示全部'
    + obj.re_num
    + '条</a></li>';
    return sContent;
  }
  /**
   * 把string转换为时间
   */
  function parseTimeStr(str){
    var arr=str.split(' ');
    var aDate=arr[0];
    var aTime=arr[1];
    var _aDate = aDate.split('-');
    var yy=_aDate[0];
    var mm=_aDate[1]-1;
    var dd=_aDate[2];
    var _aTime = aTime.split(':');
    var hh=parseInt(_aTime[0],10);
    var min=parseInt(_aTime[1],10);
    var sec=parseInt(_aTime[2],10);
    var oDate = new Date(yy,mm,dd,hh,min,sec);
    return oDate.getTime();
  }
  /**
   * 把string转换为显示的事件格式
   * @param {string} time 时间戳
   * @param {boolean} notime 精确到3天前
   */
  function parseTime(time,notime) {
    var now = new Date().getTime();
    notime = notime ? true : false;
    var before = parseInt((now - time) / 1000 / 60);
    if (before >= 60) {
      before = parseInt(before / 60);
      if (before >= 24) {
        time = parseInt(time);
        before = parseInt(before / 24);
        var total = [];
        var hour = addZero(new Date(time).getHours());
        var min = addZero(new Date(time).getMinutes());
        total.push(hour);
        total.push(':');
        total.push(min);
        if(notime) {
          if (before >= 3) {
            return '3天前';
          } else {
            return before + '天前';
          }
        }
        if (before >= 3) {
          total.unshift('3天前&nbsp;');
        } else {
          total.unshift(before + '天前&nbsp;');
        }
        return total.join('');
      } else {
        return before + '小时前';
      }
    } else {
      if(before < 3) {
        return '刚刚更新';
      }
      return before + '分钟前';
    }
  }
  /**
   * 在不足位的情况下用0补足位
   */
  function addZero(val) {
    if ((val + '').length < 2) {
      val = '0' + val;
    }
    return val;
  }
  /**
   * 获得用户信息，如果首次获得，会放入缓存中，以备下次调用
   * @param {number} uid 用户ID
   * @param {array} arr 存取用户缓存的数组
   */
  function getProfile(uid, arr) {
    var user = {};
    user.uid = uid;
    if (arthCache[uid]) {
      user.tinyurl = arthCache[uid].tinyurl;
      user.name = arthCache[uid].name;
    } else {
      for (var j = 0, len = arr.length; j < len; j++) {
        if (uid == arr[j].uid) {
          user.tinyurl = arr[j].tinyurl;
          user.name = arr[j].name;
          arthCache[uid] = {};
          arthCache[uid].tinyurl = arr[j].tinyurl;
          arthCache[uid].name = arr[j].name;
          break;
        }
      }
    }
    return user;
  }
  /**
   * 处理大多数的点击事件
   */
    function onClickListener(e) {
    e = e ? e : window.event;
    var target = e.target ? e.target : e.srcElement;
    if (_hasClass(target, 'funt1') && _hasClass(target, 'collapse')) {
	  // 展开回复 ok
	  var count = target.getAttribute('count');
      var oDiv = target.parentNode.parentNode.getElementsByTagName('ul')[0];
      if (oDiv.style.display == '') {
	    var moreCount = target.parentNode.parentNode.getElementsByTagName('textarea')[0];
	    moreCount = moreCount.getAttribute('replynum');
		if(moreCount) {
			count = (count-0) + (moreCount-0)
		}
        oDiv.style.display = 'none';
		if(count > 0) {
			count += '条';
		} else {
			count = '';
		}
        target.innerHTML = count + '回复';
      } else {
	    oDiv.style.display = '';
	    if(target.innerHTML.length == 2) {
			var textarea = target.parentNode.parentNode.getElementsByTagName('textarea')[0];
			ontextareaClick(textarea);
			textarea.focus();
		} else {
			fixShowComments(target.parentNode.parentNode);
		}
        target.innerHTML = '收起回复';
      }
    } else if (target.getAttribute('num')&&target.tagName.toUpperCase() == 'A') {
	  //显示全部回复 ok?
	  status_showAllComments(target);
    } else if (_hasClass(target, 'fwd')) {
	  //转发 焦点有点问题
    //完善后可以添加到fwdMessage
      var u = target.parentNode;
      var name = u.parentNode.firstChild.firstChild.innerHTML;
      var content = u.parentNode.firstChild.lastChild;
      var children = content.childNodes;
      content = [];
      for(var i=0,length=children.length; i<length; i++) {
        switch(children[i].nodeType) {
          case 3 : content.push(children[i].nodeValue);break;
          case 1 : content.push(handleImg(children[i]));break;
        }
      }
      _removeClass(_gel('user_status_input'),'begin');
      _gel('user_status_input').value='转自'+name+'：'+content.join('');
	  _addClass(_gel('user_status_input_out'),'on');
	  showEmoticon(_gel('user_status_input'));
	  _gel('user_status_input').focus();
	  _gel('textNow').style.display = 'none';
	  target = target.parentNode.parentNode.parentNode;
	  var sid = target.getAttribute('sid');
	  var uid = target.getAttribute('uid');
	  setFwdId(sid,uid);
    } else if (target.tagName.toLowerCase() == 'img' && target.name) {
	  //图片转向主页
      var uid = target.getAttribute("name");
      onPicClick(uid);
    } else if(target.tagName.toLowerCase() == 'textarea') {
	  ontextareaClick(target);
	} else if(target.tagName.toLowerCase() == 'a' && _hasClass(target,'face_re')) {
		//点击表情 ok
		target = target.parentNode.parentNode;
		var area = target.getElementsByTagName('textarea')[0];
		showEmoticon(area,true);
		area.focus();
	} else if(target.tagName.toLowerCase() == 'input' && _hasClass(target,'btn')) {
		//点击回复 ok
		status_addComment(target);
	} else if(_hasClass(target,'replay')) {
		//点击了回复链接 ok
		var rid = target.getAttribute('uid');
		var rname = target.getAttribute('name');
		target = target.parentNode.parentNode.parentNode.getElementsByTagName('textarea')[0];
		_addClass(target.parentNode.parentNode,'over');
		var spans = target.parentNode.parentNode.parentNode.parentNode.getElementsByTagName('span');
		var counter;
		for(var num=0; spans[num]; num++) {
			if(_hasClass(spans[num],'counter')) {
				counter = spans[num];
				break;
			}
		}
	  if(_hasClass(target, 'begin')) {
		target.value = '';
		counter.innerHTML = '0';
		_removeClass(target,'begin');
	  }
	  if(!target.getAttribute('installed')) {
		target.setAttribute('installed','yes');
		target.onblur = onareaBlur;
		counter.innerHTML = '0';
		target.onkeyup = textCounter(target,counter,140);
		target.onkeydown = textCounter(target,counter,140);
		target.onfocus = textCounter(target,counter,140);
	  }

	  target.value = '回复'+rname+'：';
	  _addClass(target.parentNode.parentNode.parentNode,'over');
	  target.setAttribute('limit',target.value.length);
	  target.setAttribute('rid',rid);
	  target.focus();
	}
  }
  
  function fixShowComments(target) {
	var lis = target.getElementsByTagName('li');
	for(var num=0; lis[num]; num++) {
		if(_hasClass(lis[num],'allReturn')) {
			lis = lis[num];
			break;
		}
	}
	if(lis.style) {
		var display = lis.style.display;
		if(!display) {
			var a = first(lis);
			status_showAllComments(a);
		}
	}
  }
  
  function ontextareaClick(target) {
	  _addClass(target.parentNode.parentNode.parentNode,'over');
	  var spans = target.parentNode.parentNode.parentNode.getElementsByTagName('span');
		var counter;
		for(var num=0; spans[num]; num++) {
			if(_hasClass(spans[num],'counter')) {
				counter = spans[num];
				break;
			}
		}
	  if(_hasClass(target, 'begin')) {
		target.value = '';
		counter.innerHTML = '0';
		_removeClass(target,'begin');
	  }
	  if(!target.getAttribute('installed')) {
		target.setAttribute('installed','yes');
		target.onblur = onareaBlur;
		counter.innerHTML = '0';
		target.onkeyup = textCounter(target,counter,140);
		target.onkeydown = textCounter(target,counter,140);
		target.onfocus = textCounter(target,counter,140);
	  }
  }
  /**
   * 显示所有的回复，即点击'显示所有X条信息'时调用
   */
  function status_showAllComments(target) {
	  var limit = target.getAttribute('num');
      target = target.parentNode;
      var obj = target.parentNode.parentNode.parentNode;
      var status_id = obj.getAttribute('sid');
      var owner_id = obj.getAttribute('uid');
      var item_div = target;
      //if (item_div.getAttribute('hasAll') > 0) {
      //  target.nextSibling.style.display = '';
      //  target.style.display = 'none';
      //} else {
        //target.style.display = 'none';
		target.innerHTML = '正在读取...';
		var content = target.parentNode.parentNode.parentNode.getElementsByTagName('textarea')[0];
		var num = content.getAttribute('replynum') || 0;
        showAllComments(target, status_id, owner_id, limit,num);
      //}
  }
  /**
   * 添加回复
   */
  function status_addComment(target) {
	var pp = target.parentNode.parentNode;
	var content = pp.getElementsByTagName('textarea')[0];
	var status_id = content.getAttribute('sid');
	var owner_id = content.getAttribute('uid');
	var rid = content.getAttribute('rid');
	if(rid && rid == 'no') {
		rid = null;
	}
	if(!_trim(content.value)) {
		content.removeAttribute('disabled');
		target.removeAttribute('disabled');
		_addClass(content,'begin');
		content.value = '添加回复';
		_removeClass(pp,'over');
		return;
	} else if(_hasClass(content,'begin')) {
		content.value = '添加回复';
		content.blur();
		return;
	}
	XN.Main.apiClient.status_addComment(status_id,owner_id, content.value,rid,function(result,ex) {
		if(!ex) {
			var li = makeReplayContent(content.value);
			pp.parentNode.insertBefore(li,pp);
			var num = content.getAttribute('replyNum');
			if(!num) {
				num = 0;
			}
			content.setAttribute('replyNum',++num);
			fixShowComments(content.parentNode.parentNode.parentNode.parentNode.parentNode);
		}else{
			dealEx(ex);
		}
		content.removeAttribute('disabled');
		target.removeAttribute('disabled');
		_addClass(content,'begin');
		content.value = '添加回复';
		_removeClass(pp,'over');
		content.blur();
	});
	content.disabled = 'true';
	target.disabled = 'true';
  }
  /**
   * 创建回复的li element
   */
  function makeReplayContent(countent) {
	var date = new Date();
	var time = [];
	time.push(date.getMonth() + 1);
	time.push('-');
	time.push(date.getDate());
	time.push('&nbsp;');
	var h = date.getHours() + '';
	if(h.length == 1) {
		h = '0' + h;
	}
	time.push(h);
	time.push(':');
	var m = date.getMinutes() + '';
	if(m.length == 1) {
		m = '0' + m;
	}
	time.push(m);
	time = time.join('');
	var li = document.createElement('li');
	var img = document.createElement('img');
	img.className = 'fl';
	img.style.width = '30px';
	img.style.height = '30px';
	img.style.float = 'left';
	img.name = oUser.id;
	img.src = oUser.img;
	var div = document.createElement('div');
	div.className = 'items';
	div.innerHTML = '<a class="font1" href="http://renren.com/profile.do?id='+oUser.id+'" target="_blank">'+oUser.name+'</a>'
					+ '&nbsp;<span class="font2 fontSmall">'
					+ time
					+ '</span><br/>'
					+ handleMsg(countent,true);
	li.appendChild(img);
	li.appendChild(div);
	return li;
  }
  /**
   * 实时显示当前字数
   */
function textCounter(field, countfield, maxlimit) {
	return function(e) {
		e=e?e:window.event;
		bIsOnEdit = true;
		var keyCode=e.keyCode||e.which||e.charCode;
		if(keyCode == 13) {
			/*加了一个parentNode*/
			var input = field.parentNode.parentNode.parentNode.getElementsByTagName('input')[0];
			status_addComment(input);
			closeEmoticon();
			return;
		}
		setTimeout(function() {
		var limit = field.getAttribute('limit');
		if(field.value.length < limit) {
			field.setAttribute('rid','no');
		}
		if (field.value.length > maxlimit){
			// if too long...trim it!
			field.value = field.value.substring(0, maxlimit);
			countfield.firstChild.nodeValue = maxlimit;
			// otherwise, update 'characters left' counter
		}else{
			countfield.firstChild.nodeValue = field.value.length;
		}
		},0);
	}
}
/**
 * 输入状态框失去焦点时调用
 */
  function onareaBlur() {
	if(inOnEm) {
		return;
	}
	if(inEm) {
		this.focus();
		return;
	}
	closeEmoticon();
	bIsOnEdit = false;
	if(!_trim(this.value)) {
		_addClass(this,'begin');
		this.value = '添加回复';
		_removeClass(this.parentNode.parentNode.parentNode,'over');
	}
  }
  
  function _trim(s){
    return s.replace(/^\s*|\s*$/g,"");
  }
  
  function showAllComments(con, status_id, owner_id, limit,num) {
    XN.Main.apiClient.status_getComment(status_id, owner_id, limit+(num-0),
      function(result, ex) {
        if (!ex) {
		  con.setAttribute('hasAll', result.length);
		  //var div = document.createElement('div');
		  con.style.display = 'none';
          for (var len = result.length, i = len - 2; i > num; i--) {
            var item = createCommentItem(result[i],status_id);
			con.parentNode.insertBefore(item,con);
            //div.appendChild(item);
          }
		  //con.parentNode.insertBefore(div,con);
        }
      })
  }
  function createCommentItem(rs,status_id) {
    var item_div = document.createElement('li');
    //item_div.className = 'item';
    var text = '';
    text = '<img src="' + rs.tinyurl
    + '" align="left" height="30" width="30" name="' + rs.uid
    + '" class="f1"></img>' + '<div class="items">'
    + '<a  target="_blank"  href="http://renren.com/profile.do?id='
    + rs.uid + '" class="font3" target="_blank">' + rs.name
    + '</a> <span class="font2 fontSmall">' + rs.time + '</span><br/>'
    + handleMsg(rs.text,true);
    if (rs.uid == oUser.id) {
      text += '</div>';
    } else {
      text += '<a class="font3 cu replay" rid="'
      + rs.uid
      + '" name="'+rs.name+'" href="javascript:void(0)">回复</a></div>';
    }
    item_div.innerHTML = text;
    return item_div;
  }
  /**
   * 处理图片的点击事件
   */
  function handleImg(dom) {
    if(aEmotions.length > 0) {
	  if(dom.tagName.toLowerCase() == 'a') {
		return dom.innerHTML;
	  }
      for(var i=0,length=aEmotions.length; i<length; i++) {
        if(dom.src == aEmotions[i].icon) {
          return aEmotions[i].emotion.replace(/\\/g,'');
        }
      }
    } else {
      getStatus(function(data){
        handleImg(dom);
      });
    }
  }

  function getStatus(callback, opt_uId) {
    var transform = opt_uId ? false : true;
    var uid = opt_uId || null;
    XN.Main.apiClient.status_gets(uid, 1, 1, function(result, ex) {
      if (!ex) {
        var data = result[0];
        if (!transform) {
          callback(data);
          return;
        }
        if (aEmotions.length > 0) {
          callback(data);
        } else {
          XN.Main.apiClient.status_getEmoticons('all', function(result,
            ex) {
            if (!ex) {
              aEmotions = result;
              for (var i = 0, length = aEmotions.length; i < length; i++) {
                aEmotions[i]['emotion'] = aEmotions[i]['emotion']
                .replace(/\\/ig, '\\\\');
                aEmotions[i]['emotion'] = aEmotions[i]['emotion']
                .replace(/\$/ig, '\\\$');
                aEmotions[i]['emotion'] = aEmotions[i]['emotion']
                .replace(/\^/ig, '\\\^');
                aEmotions[i]['emotion'] = aEmotions[i]['emotion']
                .replace(/\*/ig, '\\\*');
                aEmotions[i]['emotion'] = aEmotions[i]['emotion']
                .replace(/\./ig, '\\\.');
                aEmotions[i]['emotion'] = aEmotions[i]['emotion']
                .replace(/\+/ig, '\\\+');
                aEmotions[i]['emotion'] = aEmotions[i]['emotion']
                .replace(/\?/ig, '\\\?');
                aEmotions[i]['emotion'] = aEmotions[i]['emotion']
                .replace(/\=/ig, '\\\=');
                aEmotions[i]['emotion'] = aEmotions[i]['emotion']
                .replace(/\!/ig, '\\\!');
                aEmotions[i]['emotion'] = aEmotions[i]['emotion']
                .replace(/\|/ig, '\\\|');
                aEmotions[i]['emotion'] = aEmotions[i]['emotion']
                .replace(/\//ig, '\\\/');
                aEmotions[i]['emotion'] = aEmotions[i]['emotion']
                .replace(/\(/ig, '\\\(');
                aEmotions[i]['emotion'] = aEmotions[i]['emotion']
                .replace(/\)/ig, '\\\)');
                aEmotions[i]['emotion'] = aEmotions[i]['emotion']
                .replace(/\[/ig, '\\\[');
                aEmotions[i]['emotion'] = aEmotions[i]['emotion']
                .replace(/\]/ig, '\\\]');
                aEmotions[i]['emotion'] = aEmotions[i]['emotion']
                .replace(/\{/ig, '\\\{');
                aEmotions[i]['emotion'] = aEmotions[i]['emotion']
                .replace(/\}/ig, '\\\}');
              }
              callback(data);
            }
          })
        }
      }
    })
  }
  function handleMyStatus(data) {
    _gel('status_update').innerHTML = parseTime(parseTimeStr(data.time),true) + ':' + handleMsg(data.message);
  }
  function parseTime(time,notime) {
    var now = new Date().getTime();
    notime = notime ? true : false;
    var before = parseInt((now - time) / 1000 / 60);
    if (before >= 60) {
      before = parseInt(before / 60);
      if (before >= 24) {
        time = parseInt(time);
        before = parseInt(before / 24);
        var total = [];
        var hour = addZero(new Date(time).getHours());
        var min = addZero(new Date(time).getMinutes());
        total.push(hour);
        total.push(':');
        total.push(min);
        if(notime) {
          if (before >= 3) {
            return '3天前';
          } else {
            return before + '天前';
          }
        }
        if (before >= 3) {
          total.unshift('3天前&nbsp;');
        } else {
          total.unshift(before + '天前&nbsp;');
        }
        return total.join('');
      } else {
        return before + '小时前';
      }
    } else {
      if(before < 3) {
        return '刚刚更新';
      }
      return before + '分钟前';
    }
  }
  function addZero(val) {
    if ((val + '').length < 2) {
      val = '0' + val;
    }
    return val;
  }
  function parseTimeStr(str){
    var arr=str.split(' ');
    var aDate=arr[0];
    var aTime=arr[1];
    var _aDate = aDate.split('-');
    var yy=_aDate[0];
    var mm=_aDate[1]-1;
    var dd=_aDate[2];
    var _aTime = aTime.split(':');
    var hh=parseInt(_aTime[0],10);
    var min=parseInt(_aTime[1],10);
    var sec=parseInt(_aTime[2],10);
    var oDate = new Date(yy,mm,dd,hh,min,sec);
    return oDate.getTime();
  }
  var currentYear = (new Date()).getFullYear();
  function parseTimeStr2(str){
    var arr=str.split(' ');
    var aDate=arr[0];
    var aTime=arr[1];
    var _aDate = aDate.split('-');
    var yy=currentYear;
    var mm=_aDate[0]-1;
    var dd=_aDate[1];
    var _aTime = aTime.split(':');
    var hh=parseInt(_aTime[0],10);
    var min=parseInt(_aTime[1],10);
    var oDate = new Date(yy,mm,dd,hh,min,0);
    return oDate.getTime();
  }
  function handleMsg(str,noshut) {
    noshut = noshut ? true : false;
	str = str.replace(/\&/ig, '&amp;');
    str = str.replace(/</ig, '&lt;');
    str = str.replace(/>/ig, '&gt;');
    for (var i = 0, length = aEmotions.length; i < length; i++) {
      var pattern = new RegExp(aEmotions[i]['emotion'],"g");
      str = str.replace(pattern,'<img alt=' + aEmotions[i]['desc'] + ' src='
        + aEmotions[i]['icon'] + '>');
    }
    if(noshut) {
      return str;
    }
    //slice string
	var content = [];
	var len = 0;
	var div = document.createElement('div');
	div.innerHTML = str;
	var nodeList = div.childNodes;
	var maxLen = 9;
	for(var j=0; nodeList[j]; j++) {
		var node = nodeList[j];
		if(node.nodeType == 3) {
			var text = node.nodeValue;
			for(var k=0; text.charAt(k); k++) {
				content.push(text.charAt(k).replace(/\&/ig, '&amp;').replace(/</ig, '&lt;').replace(/>/ig, '&gt;'));
				len++;
				if(len == maxLen) {
					if(text.charAt(k+1)) {
						content.push('...');
					}
					return content.join('');
				}
			}
		} else {
			var s = '<IMG alt='+node.alt
					+ ' src='+node.src+ '>';
			content.push(s);
			len++;
			if(len == maxLen) {
				if(nodeList[j+1]) {
					content.push('...');
				}
				return content.join('');
			}
		}
	}
    return content.join('');
  }
  function showPopUp(text){
    _gel('popupcon').innerHTML = text;
    _gel('popupbox').style.display='';
    setTimeout(function(){_gel('popupbox').style.display='none';},2000);
  }
  function onCheckPermission(){
    window.open("http://app.renren.com/apps/authorize.do?api_key="
      + apiKey
      + "&next=www.google.com.hk/ig/modules/chinagadgets/renren/validatePower.html&cancel=www.google.com.hk/ig/modules/chinagadgets/renren/permission.html&ext_perm=status_update,publish_feed,read_stream&display=noad");
  }
  function _setClass(el, classname) {
    el.className = classname;
  }
  function _hasClass(ele, cls) {
    return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
  }
  function _addClass(ele, cls) {
    if (!_hasClass(ele, cls))
      ele.className += " " + cls;
  }
  function _removeClass(ele, cls) {
    if (_hasClass(ele, cls)) {
      var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
      ele.className = ele.className.replace(reg, ' ');
    }
  }
  function _gel(str){
    return document.getElementById(str);
  }
  function getElementsByClassName(node,tag,searchClass) {
    if (node.getElementsByClassName)
      return node.getElementsByClassName(searchClass);
    else {
      var classElements = new Array();
      if ( node == null )
              node = document;
      if ( tag == null )
              tag = '*';
      var els = node.getElementsByTagName(tag);
      var elsLen = els.length;
      var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
      for (i = 0, j = 0; i < elsLen; i++) {
              if ( pattern.test(els[i].className) ) {
                      classElements[j] = els[i];
                      j++;
              }
      }
      return classElements;
    }
  }
  function first(ele) {
    if(ele) {
      var first = ele.firstChild;
      if(first.nodeType != 1) {
        return next(first);
      }
      return first;
    }
  }
  
  function getLoc(dom,isScroll) {
        var loc = {};
        loc.x = pageX(dom);
		loc.y = pageY(dom);
		if(isScroll) {
			loc.y -= _gel('contentAll').scrollTop;
		}
        return loc;
    }
  
  function pageX(dom) {
        return dom.offsetParent
                ? dom.offsetLeft + pageX(dom.offsetParent)
                : dom.offsetLeft;
    }
    
    function pageY(dom) {
        return dom.offsetParent
                ? dom.offsetTop + pageY(dom.offsetParent)
                : dom.offsetTop;
    }
    
    function getHeight(ele) {
        return ele.offsetHeight || parseInt(getStyle(ele,'height'));
    }
    
    function getWidth(ele) {
        return ele.offsetWidth || parseInt(getStyle(ele,'width'));
    }
    
    function getStyle(ele,name) {
        if(ele.style[name]) {
            return ele.style[name];
        } else if(ele.currentStyle) {
            return ele.currentStyle[name];
        } else if(document.defauleView && document.defalutView.getComputedStyle) {
            name = name.replace(/[A-Z]/g,'-$1');
            name = name.toLowerCase();
            var s = document.defalutView.getComputedStyle(s,'');
            return s && s.getPropertyValue(name);
        } else {
            return null;
        }
    }
  
  function next(ele) {
    if(ele) {
      var next = ele.nextSibling;
      while(next && next.nodeType != 1) {
        next = next.nextChild;
      }
      return next;
    }
  }
  
  function getPageDiv(num,selected,callback) {
    var total = parseInt(num/NUM_PER_PAGE);
    if(total < (selected-1)) {
      return null;
    }
    if(_gel('pagination')) {
      _gel('pagination').parentNode.removeChild(_gel('pagination'));
    }
    var div = document.createElement('div');
    div.id = 'pagination';
    _addClass(div,'pageBox');
    var last = num/NUM_PER_PAGE;
    if(last <= 1) {
      div.style.display = 'none';
    }
    total = total > 4 ? 4 : total;
    for(var i=0; i<=total; i++) {
      var a = document.createElement('a');
      a.href = 'javascript:void(0)';
      a.innerHTML = i+1;
      if((i+1) == selected) {
        _addClass(a,'pageOver');
      }
      a.onclick = function() {
                  if(!_hasClass(this,'pageOver')) {
                    var pages = _gel('pagination').getElementsByTagName('a');
                    for(var key=0; pages[key]; key++) {
                      _removeClass(pages[key],'pageOver');
                    }
                    _addClass(this,'pageOver');
                    _gel('pagination').style.display = 'none';
                    callback(this);
                    //_gel('pagination').parentNode.removeChild(_gel('pagination'));
                  }
      }
      div.appendChild(a);
    }
    return div;
  }
})()
